<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background: greenyellow;
            margin: 0;
            padding: 0;
        }

        .ball {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            position: relative;
            left: 20px;
            background: blanchedalmond;
            top: 20px;
        }
    </style>
</head>

<body>
    <div class="ball">

    </div>
    <script>
        let ball = document.querySelector(".ball");
        let ballW = ball.clientWidth;
        console.info(ballW)
        let ballH = ball.clientHeight;
        console.info(ballH)
        let clientWidth = document.documentElement.clientWidth;
        let clientHeight = document.documentElement.clientHeight;
        let maxLeft = clientWidth - ballW;
        console.log(maxLeft)
        let maxTop = clientHeight - ballH;
        let distanceX = 1;
        let distanceY = 1;
        let inter = setInterval(function () {
            let ballReat = ball.getBoundingClientRect();
            let ballReatLeft = ballReat.left;
            let ballReatTop = ballReat.top;
            let left = ballReatLeft + distanceX;
            console.log(left)
            // console.log(ballReatLeft)
            // console.log(distanceX)
            let top = ballReatTop + distanceY;
            if (left < 0) {
                left = 0;
                distanceX = -distanceX;
            }
            if (left > maxLeft) {
                // console.info("left")
                left = maxLeft;
                distanceX = -distanceX;
            }
            if (top < 0) {
                top = 0;
                distanceY = -distanceY;
            }
            if (top > maxTop) {
                top = maxTop;
                distanceY = -distanceY;
            }
            console.log(distanceX)
            ball.style.left = left + "px";
            ball.style.top = top + "px";
        }, 2)
        // clearInterval(inter)
    </script>

</body>

</html>